// pages/eating/eating.js
const app = getApp();
const tool = require('../../utils/util')
const scan = require('../../utils/scanCode')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        seat_id: 0,
        store_id: 0,
        merchant_id: 0,
        storeType:'',
        people: 1,
        source_people: 0,
        order_seat_sn: '',
        tradeInfo: {
            people: 0,
            order: {
              products: []
            },
            price: 0,
            created_at: ''
        },
        orderMenu: {
            people: 0,
            order: {
                products: {
                    audited:[],
                    waited:[]
                }
            },
            price: 0,
            created_at: '',
            order_seat_sn: ''
        },
        eating: false,
        status_close: 3,
        status_payed: 2,
        status_finish: 4,
        showScan: true,
        hasSeatProduct: false,
        hasOwnProduct: false,
        hasTrade: false,
        orderMenuStatus: true,
        count: 0,
        is_open_cart:1,
        is_first_open:0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log("show eating")
        console.log(options)
        if(options['mid'] && options['id']){
            scan.saveScanQrcodeResult('', options['mid'], tool.objectToString(options), options['id'])
        }
        if(options['goeat']){
            this.openTabMenu()
        }
        this.data.is_first_open = 1
    },

    loadOrder: function (refresh) {
        var that = this
        var obj = scan.getScanQrcode()
        console.log(obj)
        if (obj && obj['sn']) {
            /** 已下单 **/
            getApp().http.request({
                url: "/api/v2/order?order_seat_sn=" + obj['sn'],
                data: {},
                method: 'get',
                success: function (res) {
                  if (that.data.orderMenuStatus && refresh) {
                    wx.showToast({
                      title: '已下单列表刷新成功',
                        duration:2000
                    })
                  }
                  var response = res.data
                  console.log(res)
                  console.log(response['data']['order']['products'])
                  var temp = that.data.orderMenu
                  console.log("temp")
                  console.log(that.data.orderMenu)

                  temp['order']['products'] = response['data']['order']['products']
                  temp.created_at = response.data['order']['created_at']
                  temp.people = response.data['people']
                  temp.order_seat_sn = response.data['order']['order_seat_sn']
                  if ((response.data['order']['products']['audited'].length > 0) || (response.data['order']['products']['waited'].length > 0))  {
                      for (var i = 0; i < response.data['order']['products']['audited'].length; i++) {
                          temp.price += response.data['order']['products']['audited'][i]['price'] * response.data['order']['products']['audited'][i]['quantity']
                      }
                      // for (var i = 0; i < response.data['order']['products']['waited'].length; i++) {
                      //     temp.price += response.data['order']['products']['waited'][i]['price'] * response.data['order']['products']['waited'][i]['quantity']
                      // }
                      that.setData({
                          // showScan: false,
                          hasTrade: true,
                          orderMenu: temp
                      })
                  }
                  else {
                    var temp = that.data.orderMenu
                    temp.people = 0
                    temp.order.products.audited = []
                    temp.order.products.waited = []
                    temp.created_at = ''
                    temp.price = 0
                    that.setData({
                      // showScan: false,
                      hasTrade: false,
                      orderMenu: temp
                    })
                  }

                    // console.log(res.data)
                }
            })
            /** 未下单 **/
            console.log(obj)
            getApp().http.request({
              url: "/api/v1/menu?merchant_id=" + obj['mid'] + "&seat_id=" + obj['seat_id'],
                data: {},
                method: 'POST',
                success: function (res) {
                  if (!that.data.orderMenuStatus && refresh) {
                    wx.showToast({
                      title: '未下单列表刷新成功',
                        duration:2000
                    })
                  }
                    var response = res.data
                    console.log(response)
                    var temp = that.data.tradeInfo
                    temp.order.products = response.data['products']
                    temp.created_at = response.data['info']['created_at']
                    temp.people = response.data['info']['people']
                    if (response.data['products'].length > 0) {
                      temp.price = 0
                      for (var i = 0; i < response.data['products'].length; i++) {
                          temp.price += response.data['products'][i]['price'] * response.data['products'][i]['qty']
                      }
                      that.setData({
                          // showScan: false,
                          hasSeatProduct: true,
                          tradeInfo: temp
                      })
                    }
                    else {
                      var temp = that.data.tradeInfo
                      temp.people = 0
                      temp.order.products = []
                      temp.created_at = ''
                      temp.price = 0
                      that.setData({
                        // showScan: false,
                        hasSeatProduct: false,
                        tradeInfo: temp
                      })
                    }
                    console.log(res.data)
                }
            })
        }
    },
    /**
     * 增加人数
     */
    plusCounter: function () {
      if (this.data.orderMenuStatus) {
        var temp = this.data.orderMenu
        temp.people += 1
        this.setData({
          orderMenu: temp
        })
      } else {
        var temp = this.data.tradeInfo
        temp.people += 1
        this.setData({
          tradeInfo: temp
        })
      }
    },
    /**
     * 减少人数
     */
    decCounter: function () {
        console.log(this.data.people)
        if (this.data.orderMenuStatus) {
          var temp = this.data.orderMenu
          if (temp.people > 1 && temp.people > this.data.source_people) {
            temp.people -= 1
            this.setData({
              orderMenu: temp
            })
          }
        } else {
          var temp = this.data.tradeInfo
          if (temp.people > 1 && temp.people) {
            temp.people -= 1
            this.setData({
              tradeInfo: temp
            })
          }
        }
    },

    /**
     * 加菜接口调用
     */
    addProduct: function () {
        let obj = scan.getScanQrcode()
        if (obj['path']) {
            // var parmArray = tool.queryToObject(res.data)
            wx.navigateTo({
                url: "../cart/cart?merchant_id=" + obj['mid'] + "&seat_id=" + obj['seat_id'] + "&storeType=加菜"
            })
        }
    },
    /**
     * 提交人数变更
     */
    addPeople: function () {
        getApp().http.request({
            url: "/api/v1/order/people?order_seat_sn=" + this.data.order_seat_sn + '&people=' + this.data.people,
            data: {},
            method: 'POST',
            success: function (res) {
                wx.showToast({
                    title: '更改人数成功!',
                    duration:2000
                })
            }
        })
    },

    doPay: function (e) {

        var  order_sn = e.currentTarget.dataset.sn;

        getApp().http.request({
            url: '/api/v1/trade/request_pay',
            data: {
                sn: order_sn,
            },
            dataType: 'json',
            success: function (res) {
                console.log(res.data.code)
                console.log(res.data.data.wx)
                if (res.data.code == 500){
                    wx.showToast({
                        title: res.data.msg,
                        duration: 2000,
                    })
                }else{
                    wx.requestPayment({

                        'timeStamp': res.data.data.wx.timeStamp,
                        'nonceStr': res.data.data.wx.nonceStr,
                        'package': res.data.data.wx.package,
                        'signType': res.data.data.wx.signType,
                        'paySign': res.data.data.wx.paySign,
                        'success': function (res) {
                            let newVar = {url: "/pages/eating/eating"};
                            console.log(newVar)
                            wx.switchTab(newVar)
                        },
                        'fail': function (res) {
                        },
                        'complete': function (res) {
                        }
                    })
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    beforeScan:function(){
        if (this.data.is_first_open) {
            wx.showLoading({
                title: '努力加载菜单中',
            })
        }
    },
    afterScan:function(){
        this.data.is_first_open = 0
        wx.hideLoading()
    },
    finishScan:function(){
        var that = this
        if (!that.data.showScan) {
            if (that.isTabMenu()) {
                that.refreshMenu()
            }else{
                that.openTabMenu()
                that.refreshTradeOrder(function(reponse){
                    that.clearDesktop(reponse['data']['order']['status']);
                })
            }
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        console.log("on show")
        let obj = scan.getScanQrcode()
        if (obj && obj['path']) {
            this.beforeScan()
            this.doScanAction(obj['path'],this.finishScan)
        }

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.data.is_first_open = 0
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },



    doScanAction: function (query, cb) {
        var that = this
        var obj = tool.queryToObject(query)
        scan.saveScanQrcodeResult('', obj['mid'], query, obj['id'])
        console.log(obj)
        getApp().http.request({
            url: '/api/v2/seat/scan',
            data: obj,
            complete: function(){
                that.afterScan()
            },
            success: function (res) {
                var response = res.data;
                console.log(response)
                
                if (response.code == 200) {
                  
                    scan.setItem('order_seat_sn', response.data['order_seat_sn'])
                    that.setData({
                      count: response.data['own_product_count']
                    })
                    if (response.data.has_own_product || response.data.has_seat_product || response.data.has_trade) {
                      
                        var data = {};
                        that.setData({
                            showScan:false,
                            hasSeatProduct: response.data['has_seat_product'],
                            hasOwnProduct: response.data['has_own_product'],
                            hasTrade: response.data['has_own_product']
                        })
                        if (response.data.has_own_product && !response.data.has_seat_product && !response.data.has_trade) {
                            // that.order_combine_to_seat()
                        }
                        that.setData({
                          showScan: false
                        })
                        if (cb){
                            cb(response)
                        }
                    } else {
                        if (that.data.is_open_cart){
                            that.data.is_open_cart = 0
                            wx.navigateTo({
                                url: '../cart/cart?id=' + response.data.mid + '&storeType=点餐'
                            })
                        }
                    }
                }else{
                    wx.showToast({
                        title: response.msg,
                        icon: 'success',
                        duration: 2000,
                        success: function () {

                        }
                    })
                }
            }
        })


    },
    /**
     * 开启扫码功能
     */
    ///pages/scan-loading/scan-loading
    openscan: function () {
        var that = this
        that.data.is_open_cart = 1
        wx.scanCode({
            success: (res) => {
                console.log(res)
                let obj = tool.parseQueryString(res.path)
                let query = tool.objectToString(obj);
                wx.showToast({
                    title: '扫码成功',
                    icon: 'success',
                    duration: 1500,
                    success: function () {
                        that.beforeScan()
                        that.doScanAction(query)
                    }
                })
            }
        })
    },
    closeSeat: function (order_seat_sn) {
        var that = this
        wx.showModal({
            title: '提示',
            content: '确认要离开吗?',
            success: function (res) {
                if (res.confirm) {
                   that.clearLiveDesktopData()
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })

    },
    xxxx: function (order_seat_sn) {
        var that = this
        wx.showModal({
            title: '提示',
            content: '确认要关闭订单吗?',
            success: function (res) {
                if (res.confirm) {
                    var info = scan.getScanQrcode()
                    getApp().http.request({
                        url: "/api/v1/trade/close?order_seat_sn=" + info['sn'],
                        data: {},
                        success: function (res) {
                            var reponse = res.data;


                        }
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })

    },
    clearLiveDesktopData:function(){
        var that = this
        scan.clearScanData()
        that.setData({
            showScan: true
        })
        that.data.is_open_cart = 1
        that.data.is_first_open = 1
    },
    clearDesktop: function(status){
        var that = this
        if (status == that.data.status_close ||
            // status == that.data.status_payed ||
            status == that.data.status_finish) {
            wx.showToast({
                title: '用餐已结束!',
                icon: 'success',
                duration: 2000,
                complete: function () {
                  that.clearLiveDesktopData()
                }
            })
        }
    },

    /**
     * 合并自己的菜单到餐桌
     */
    order_combine_to_seat: function () {
        let obj = scan.getScanQrcode()
        console.log(obj)
        if (obj && obj['sn'] && obj['path'] && obj['mid']) {
            wx.navigateTo({
                url: '../order-combine-to-seat/order-combine-to-seat?merchant_id=' + obj['mid'] + '&seat_id=' + obj['seat_id']
            })
        }
    },

    /**
     * 将餐桌上的菜单提交下单
     */
    order: function () {
        var that = this
        let obj = scan.getScanQrcode()
        console.log(obj)
        if (obj && obj['sn']) {
            if (that.data.tradeInfo.people > 0 || that.data.orderMenu.people > 0) {
                wx.showModal({
                    title: '提示',
                    content: '确认提交吗？',
                    success: function (res) {
                        if (res.confirm) {
                            getApp().http.request({
                                url: "/api/v1/menu/to_order?seat_id=" + obj['seat_id'],
                                data: {},
                                success: function (res) {
                                    console.log(res)
                                    var obj = scan.getScanQrcode()
                                    console.log(obj)
                                    if (obj && obj['sn'] && that.data.tradeInfo.people) {
                                        getApp().http.request({
                                            url: "/api/v1/order/people?order_seat_sn=" + obj['sn'] + '&people=' + that.data.tradeInfo.people,
                                            data: {},
                                            method: 'POST',
                                            success: function (resOrder) {
                                                that.refreshMenu()
                                                wx.showToast({
                                                    title: '下单成功！',
                                                    duration:2000
                                                })
                                            }
                                        })
                                    }else{
                                        that.refreshMenu()
                                        wx.showToast({
                                            title: res.data.msg,
                                            duration:2000
                                        })
                                    }
                                }
                            })
                        }
                    }
                })
            } else {
                wx.showToast({
                    title: '请设置就餐人数',
                    icon: '',
                    image: '',
                    duration: 2000,
                    mask: true,
                    success: function (res) {
                    },
                    fail: function (res) {
                    },
                    complete: function (res) {
                    },
                })
            }
        }
    },


    /**
    * 添加单品
    */
    addOrder: function (e) {
      var that = this
      let obj = scan.getScanQrcode()
      console.log(obj)
      if (obj && obj['sn'] && obj['mid'] && obj['seat_id']) {
        var id = e.currentTarget.dataset.id
        var qty = parseInt(e.currentTarget.dataset.qty) + 1
        var product = "id=" + id + "&qty=" + qty
        getApp().http.request({
          url: "/api/v1/menu/save?merchant_id=" + obj['mid'] + "&seat_id=" + obj['seat_id'] + "&product=" + encodeURIComponent(product) + "&people=" + that.data.tradeInfo.people + "&meno=加菜",
          data: {},
          method: "get",
          success: function (res) {
            console.log(res)
            if (res.data.code != 200) {
                wx.showToast({
                    title: res.data.msg,
                    duration:2000
                })
            }else{
                that.refreshMenu()
            }
          }
        })
      }
    },
    /**
    * 删除单品
    */
    minuOrder: function (e) {
      var that = this
      let obj = scan.getScanQrcode()
      console.log(obj)
      if (obj && obj['sn'] && obj['mid'] && obj['seat_id']) {
        var id = e.currentTarget.dataset.id
        var qty = parseInt(e.currentTarget.dataset.qty) - 1
        var product = "id=" + id + "&qty=" + qty
        console.log("minu "  +  product)
        if (qty > 0) {
          getApp().http.request({
            url: "/api/v1/menu/save?merchant_id=" + obj['mid'] + "&seat_id=" + obj['seat_id'] + "&product=" + encodeURIComponent(product) + "&people=" + that.data.tradeInfo.people + "&meno=加菜",
            method: 'get',
            data: {},
            success: function (res) {
                console.log(res)
                if (res.data.code != 200) {
                    wx.showToast({
                        title: res.data.msg,
                        duration:2000
                    })
                }else{
                    that.refreshMenu()
                }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '是否删除该菜单',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '',
            confirmText: '确定',
            confirmColor: '',
            fail: function(res) {},
            success: function(res) {
              if (res.confirm) {
                getApp().http.request({
                  url: "/api/v1/menu/save?merchant_id=" + obj['mid'] + "&seat_id=" + obj['seat_id'] + "&product=" + encodeURIComponent(product) + "&people=" + that.data.tradeInfo.people + "&meno=加菜",
                  method: 'POST',
                  data: {},
                  success: function (res) {
                    console.log(res)
                    if (res.data.code == '200') {
                      getApp().http.request({
                        url: "/api/v1/order/people?order_seat_sn=" + that.data.order_seat_sn + '&people=' + that.data.people,
                        data: {},
                        method: 'POST',
                        success: function (res) { }
                      })
                      that.refreshMenu()
                    }
                  }
                })
              }
            },
          })
        }
      }
    },
    refreshMenu:function(cb){
        var that = this
        var obj = scan.getScanQrcode()
        getApp().http.request({
            url: "/api/v1/menu?merchant_id=" + obj['mid'] + "&seat_id=" + obj['seat_id'],
            data: {},
            method: 'GET',
            success: function (res) {

                var response = res.data
                var code = response.code
                if (code == 200) {
                    console.log(response)
                    var temp = that.data.tradeInfo
                    temp.order.products = response['data']['products']
                    temp.created_at = response['data']['info']['created_at']
                    temp.people = response['data']['info']['people']
                    if (response['data']['products'].length > 0) {
                        temp.price = 0
                        for (var i = 0; i < response['data']['products'].length; i++) {
                            temp.price += response['data']['products'][i]['price'] * response['data']['products'][i]['qty']
                        }
                        that.setData({
                            hasSeatProduct: true,
                            tradeInfo: temp
                        })
                    } else {
                        var temp = that.data.tradeInfo
                        temp.people = 0
                        temp.order.products = []
                        temp.created_at = ''
                        temp.price = 0
                        that.setData({
                            hasSeatProduct: false,
                            tradeInfo: temp
                        })
                    }

                    if (cb){
                        cb(response)
                    }
                }else{
                    wx.showToast({
                        title: res.data.msg,
                        duration:2000
                    })
                }
            }
        })
    },
    refreshTradeOrder:function(cb){
        var that = this
        var obj = scan.getScanQrcode()
        getApp().http.request({
            url: "/api/v2/order?order_seat_sn=" + obj['sn'],
            data: {},
            method: 'get',
            success: function (res) {

                var response = res.data
                var code  = response.code
                if (code == 200) {

                    console.log(res)
                    console.log(response['data']['order']['products'])
                    var temp = that.data.orderMenu
                    console.log("temp")
                    console.log(that.data.orderMenu)

                    temp['order']['products'] = response['data']['order']['products']
                    temp.created_at = response['data']['order']['created_at']
                    temp.people = response['data']['people']
                    temp.order_seat_sn = response['data']['order']['order_seat_sn']
                    temp.price = 0
                    if ((response['data']['order']['products']['audited'].length > 0) || (response['data']['order']['products']['waited'].length > 0))  {
                        for (var i = 0; i < response['data']['order']['products']['audited'].length; i++) {
                            temp.price += response['data']['order']['products']['audited'][i]['price'] * response['data']['order']['products']['audited'][i]['quantity']
                        }
                        that.setData({
                            hasTrade: true,
                            orderMenu: temp
                        })
                    } else {
                        var temp = that.data.orderMenu
                        temp.people = 0
                        temp.order.products.audited = []
                        temp.order.products.waited = []
                        temp.created_at = ''
                        temp.price = 0
                        that.setData({
                            hasTrade: false,
                            orderMenu: temp
                        })
                    }

                    if (cb){
                        cb(response)
                    }
                }else{
                    wx.showToast({
                        title: response.msg,
                        duration:2000
                    })
                }
                // console.log(res.data)
            }
        })
    },
    openTabTrade:function(e){
        this.setData({
            orderMenuStatus: true
        })
        this.refreshTradeOrder()
    },
    refreshTradeWithTip: function(){
        var that = this

        this.refreshTradeOrder(function(response){
            wx.showToast({
                title: '已下单列表刷新成功',
                duration:1000,
                complete: function(){
                    that.clearDesktop(response['data']['order']['status']);
                }
            })
        })
    },
    openTabMenuWithTip: function(){
        var that = this
        this.refreshMenu(function(response){
            wx.showToast({
                title: '菜单列表刷新成功',
                duration:2000
            })
        })
    },
    openTabMenu:function(e){
        console.log("openTabMenu")
        this.setData({
            orderMenuStatus: !true
        })
        this.refreshMenu()
    },
    isTabMenu : function(){
        return this.data.orderMenuStatus == false
    }
})